package com.fanshuai.mybatis_plus.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fanshuai.mybatis_plus.domain.User;
import com.fanshuai.mybatis_plus.entity.UserEntity;
import com.fanshuai.mybatis_plus.mapper.UserMapper;
import com.fanshuai.mybatis_plus.repository.UserRepository;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class UserRepositoryImpl implements UserRepository {
    @Resource
    private UserMapper userMapper;

    private UserEntity toEntity(User user) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(user, userEntity);

        return userEntity;
    }

    private User toDomain(UserEntity userEntity) {
        User user = new User();
        BeanUtils.copyProperties(userEntity, user);

        return user;
    }

    @Override
    public void insert(User user) {
        userMapper.insert(toEntity(user));
    }

    @Override
    public void update(User user) {
        UserEntity entity = toEntity(user);
        userMapper.updateById(entity);
    }

    @Override
    public void delete(long uid) {
        userMapper.deleteById(uid);
    }

    @Override
    public User query(long uid) {
        return toDomain(userMapper.selectById(uid));
    }

    @Override
    public List<User> queryAll() {
        List<UserEntity> userEntities = userMapper.selectList(new QueryWrapper<>());
        if (CollectionUtils.isEmpty(userEntities)) {
            return new ArrayList<>();
        }

        return userEntities.stream().map(this::toDomain).collect(Collectors.toList());
    }

    @Override
    public Page<User> queryPage(int page, int size) {
        Page<UserEntity> page1 = new Page<>(page, size);
        page1 = userMapper.selectPage(page1, new QueryWrapper<>());


        Page<User> page2 = new Page<>();
        BeanUtils.copyProperties(page1, page2, "records");

        List<UserEntity> list = page1.getRecords();
        if (CollectionUtils.isEmpty(list)) {
            page2.setRecords(new ArrayList<>());
        } else {
            page2.setRecords(list.stream().map(this::toDomain).collect(Collectors.toList()));
        }

        return page2;
    }
}
